#include "controller.h"

void Controller::connectWifi()
{
    /* Server and IP address ------------------------------------------------------*/
    // WiFiServer server(80); // Wifi server exemplar using port 80
    // IPAddress myIP;        // IP address in your local wifi net
    /* SSID and password of your WiFi net ----------------------------------------*/
    // const char *ssid = "ChinaNet189_H9T2"; //"your ssid";
    // const char *password = "flex4000chiJ";   //"your password"
    const char *ssid = "1307";         //"your ssid";
    const char *password = "hxs09011"; //"your password";

    /* Static IP address Settings ------------------------------------------------*/
    // IPAddress staticIP(10, 0, 0, 49);
    // IPAddress gateway(10, 0, 0, 1);
    // IPAddress subnet(255, 255, 255, 0);
    // IPAddress dns(8, 8, 8, 8);
    IPAddress staticIP(192, 168, 10, 49);
    IPAddress gateway(192, 168, 10, 1);
    IPAddress subnet(255, 255, 255, 0);
    IPAddress dns(8, 8, 8, 8);

    if (WiFi.config(staticIP, gateway, subnet, dns, dns) == false)
    {
        Serial2.println("Configuration failed.");
    }

    // Applying SSID and password
    WiFi.begin(ssid, password);

    // Waiting the connection to a router
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial2.print(".");
    }
}

void Controller::connectWifiMutiple()
{
    WiFiMulti wifiMulti;
    WiFi.mode(WIFI_STA);
    wifiMulti.addAP("1307", "hxs09011");
    wifiMulti.addAP("ChinaNet189_H9T2", "flex4000chiJ");
    wifiMulti.addAP("Leon's iPhone 13", "liyang0224");

    // Waiting the connection to a router
    Serial2.print("[Wifi] connecting.");
    int _tryCount = 0; // retry
    while (wifiMulti.run() != WL_CONNECTED)
    {
        Serial2.print(".");
        delay(500);
        if (_tryCount++ > 20)
        {
            throw Error::WifiException();
        }
    }
    Serial2.print("\n");
    Serial2.printf("[Wifi] connected ssid: %s, ip: %s \n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
}

void Controller::setup()
{
    
}

void Controller::loop()
{
    try
    {
        connectWifiMutiple();
        apiWeather.call();
        Api::Data apiData = apiWeather.getData();
        apiData.loadHardware(hardwareHelper);
        pageWeather.show(apiData);
    }
    catch (Error::WifiException &ex)
    {
        Serial2.println("[System] loop error");
        pageSystem.showErrorWifi();
    }
    catch (Error::HttpException &ex)
    {
        Serial2.println("[System] loop error");
        pageSystem.showErrorHttp();
    }
    catch (...)
    {
        Serial2.println("[System] loop error");
        pageSystem.showErrorWifi();
    }
}

void Controller::sleep(int seconds)
{
    // sleep like baby!!!!!
  esp_sleep_enable_timer_wakeup(seconds * uS_TO_S_FACTOR);
  esp_deep_sleep_start();
}
